<?php
namespace app\api\controller\orderhawa;

use app\api\controller\Base;
use app\api\controller\mytool\Sendmessage;
use app\api\controller\Pub;
use app\common\model\company\Company;
use app\common\model\company\Contract;
use app\common\model\orderdata\Goods;
use app\common\model\orderhawa\Hawa;
use app\common\model\orderhawa\HawaList;
use app\common\model\orderhawa\ReceiptCompany;
use app\common\model\power\Rolepower;
use app\common\model\quotation\QuotationList;
use app\common\model\transit\Transitcompany;
use app\common\model\transit\TransitDriver;
use app\common\model\transit\TransitEscort;
use app\common\model\transit\Transport;
use app\common\model\user\User as UserModel;
use think\facade\Env;
use think\File;
use app\common\model\rebate\RebateList;

class Orderhawabuss extends Base
{
    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize();
        self::is_login();
        Rolepower::powerguard(201001);
    }
    /**
     * 获取合同信息
     * @return [type] [description]
     */
    public function getcontractlist()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr();
        }
        $data = Contract::getcompanycontractlist($id);
        return myok($data);
    }

    /**
     * 获取企业列表
     * @return [type] [description]
     */
    public function getcompanylist()
    {
        $key   = trim(input('searchkey'));
        if($key=="%"){return moerr('非法参数');}
        $idata = input('get.');
        if (empty($idata['lat'])) {
            //没有定位直接显示关键词
            $sdata = ['where' => [['Name', 'like', '%' . $key . '%']]];

        } else {
            $sdata['field'] = [str_distance($idata['lat'], $idata['lon'])];
            $sdata['order'] = 'distance';
            if (!empty($key)) {
                //有定位有关键词的
                $sdata['where'] = [['Name', 'like', '%' . $key . '%']];
            } else {
                //没有的默认为初始化
                $sdata['limit'] = '6';
            }
        }
        $sdata['Type'] = 'company';
        $data          = Company::usergetlist($sdata, 'buss', false);
        return myok($data);
    }

    /**
     * 代替用户下单
     * @return [type] [description]
     */
    public function createorder()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        $data = input('post.');

        //判断是否已经选择运输工具
        if (empty($data['TranSportId'])) {
            if (!empty($data['State']) && $data['State'] == HawaList::STATETRANSPORT) {
                return myerr('请选择运输工具');
            }
        }

        //格化式合同货物列表数据
        if (!empty($data['Cont_Details'])) {
            $data['Cont_Details'] = json_array($data['Cont_Details'], true);
        }

        //获取产品订单信息
        $data['goodlist']    = explode(',', $data['goodlist']);
        $data['valuelist']   = explode(',', $data['valuelist']);
        $data['Box']         = explode(',', $data['Box']);
        $data['BoxCount']    = explode(',', $data['BoxCount']);
        $data['GoodName']    = explode(',', $data['GoodName']);
        $data['ObjectState'] = explode(',', $data['ObjectState']);
        $data['Harmful']     = explode(',', $data['Harmful']);
        //合同子订单与货物订单的关联
        if (!empty($data['Cont_DedutNum'])) {
            $data['Cont_DedutNum'] = explode(',', $data['Cont_DedutNum']);
            $data['Cont_Id']       = explode(',', $data['Cont_Id']);
        }

        //删去为空的产品
        foreach ($data['valuelist'] as $key => $value) {
            if (empty($value)) {
                unset($data['goodlist'][$key]);
                unset($data['valuelist'][$key]);
            }
        }
        if (HAWAQUOT == 'acco') {
            //获取报价信息
            $quot = QuotationList::get_create_question($data);
            if (!$quot['code']) {
                return myerr($quot['msg']);
            }
            $data['quot'] = $quot['msg'];
        }

        //创建终端订单
        //由于合同创建也需要验证操作，所以在
        //创建合同验证没问题后直接在模型中进行合同抵扣
        $hawa = HawaList::screate($data, 'buss');
        if (!$hawa['code']) {
            return myerr($hawa['msg']);
        }
        $hawa = $hawa['msg'];

        if ($hawa->State == HawaList::STATEWAIT) {
            //通知运输单位或者运输公司的收集员
            $sb = Sendmessage::Orderhawa(2, $hawa->HawaListId, $hawa->toArray());
            if (!$sb['code']) {
                return myok('下单成功，请告知运输单位接单。');
            }
            return myok('下单成功，已通知运输单位');
        } elseif ($hawa->State == HawaList::STATEWAITOK) {
            $sb = Sendmessage::Orderhawa(3, $hawa->HawaListId, $hawa->toArray());
            if (!$sb['code']) {
                return myok('下单成功，请告知产废单位。');
            }
        } elseif ($hawa->State == HawaList::STATETRANSPORT) {
            $sb = Sendmessage::Orderhawa(4, $hawa->HawaListId, $hawa->toArray());
            if (!$sb['code']) {
                return myok('下单成功，请提示产废单位确认重量');
            }
        } else {
            return myerr('下单成功，通知产废单位失败');
        }
        return myok('下单成功，已通知产废单位');
    }

    /**
     * 获取订单列表
     * @return [type] [description]
     */
    function list() {
        $data = input('get.');
        $data = init_where($data);
        $list = HawaList::usergetlist($data, 'buss');

        foreach ($list['list'] as $key => $value) {
            if (empty($value['companyinfo']['Name'])) {
                $list['list'][$key]['Name'] = '暂未完善名称';
            } else {
                $list['list'][$key]['Name'] = $value['companyinfo']['Name'];
            }
        }
        $list['tr']['title'] = ['产废单位', '下单时间', '订单状态', '查看'];
        $list['tr']['key']   = ['Name', 'UpTime', 'State', 'HawaListId'];
        return myok($list);
    }

    /**
     * 地图查看订单（分配使用）
     * @return [type] [description]
     */
    public function maplist()
    {
        $data                   = input('post.');
        $data['state'] = empty($data['state']) ? 1 : $data['state'];
        $data                   = init_where($data);
        $list                   = HawaList::usergetlist($data, 'buss', false);
        foreach ($list['list'] as $key => $value) {
            if (!empty($value['companyinfo'])) {
                $list['list'][$key] = array_merge($list['list'][$key], $value['companyinfo']);
            }
            if (empty($list['list'][$key]['Name'])) {
                $list['list'][$key]['Name'] = '暂未完善名称';
            }
        }
        $list['tr']['title'] = ['产废单位', '下单时间', '订单状态', '查看'];
        $list['tr']['key']   = ['Name', 'UpTime', 'State', 'HawaListId'];
        return myok($list);
    }

    /**
     * 获取企业信息,然后下单
     * @return [type] [description]
     */
    public function getcompanyinfo()
    {
        $id = input('id');
        if (!empty($id)) {
            $data['companyinfo'] = Company::user_getinfo($id);
        } else {
            $data['companyinfo'] =[];
        }
        $data['companyinfo']              = Company::user_getinfo($id);
        $data['goodsbox']                 = GOODSBOX;
        $data['hawaquot']                 = HAWAQUOT;
        $data['mycompanyinfo']['Name']    = COMPANYALLNAME;
        $data['mycompanyinfo']['Address'] = COMPANYADDRESS;
        $sdata['order']                   = 'TransitCompanyId desc';
        $user = UserModel::getinfo();
        if($user->Role==107){
            $data['TransitCompany']           = Transitcompany::usergetlist($sdata, 'tran', false); 
        }else{
            $data['TransitCompany']           = Transitcompany::usergetlist($sdata, 'mana', false);
        }
        
        $data['TranSport']                = Transport::usergetlist($sdata, 'buss', false);
        $data['TransitDriver']            = TransitDriver::usergetlist($sdata, 'buss', false);
        $data['TransitEscort']            = TransitEscort::usergetlist($sdata, 'buss', false);
        $data['TRANSITESCORT']            = TRANSITESCORT;
        $data['quickselect']              = Goods::get_ordernumber_list(QUICK_ORDERHAWA_ORDERNUMBER);
        //获取收集企业信息
        if(get_config_value('power_double_receipt_company')==true){
            $data['receipt_company_list']   = ReceiptCompany::select();
        }
        return myok($data);
    }

    /**
     * 获取订单信息
     * @return [type] [description]
     */
    public function getinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        $data = HawaList::getinfo($id, 'buss');
        if (!$data['code']) {
            return myerr($data['msg']);
        }
        $data                   = $data['msg'];
        $data['CELLPHONE']      = CELLPHONE;
        $data['goodsbox']       = GOODSBOX;
        $sdata['order']         = 'TransitCompanyId desc';
        $data['TransitCompany'] = Transitcompany::usergetlist($sdata, 'mana', false);
        $data['TranSport']      = Transport::usergetlist($sdata, 'buss', false);
        $data['TransitDriver']  = TransitDriver::usergetlist($sdata, 'buss', false);
        $data['TransitEscort']  = TransitEscort::usergetlist($sdata, 'buss', false);
        $data['TRANSITESCORT']  = TRANSITESCORT;

        $data['mycompanyinfo']['Name']    = COMPANYALLNAME;
        $data['mycompanyinfo']['Address'] = COMPANYADDRESS;

        //获取收集企业信息
        if(get_config_value('power_double_receipt_company')==true){
            $data['receipt_company_list']   = ReceiptCompany::select();
        }
        //服务费信息
        if(get_config_value('switch_Rebate')){
            $rebate = new RebateList();
            $data['rebate'] = $rebate->get_view_info($id,'orderhawa');
        }
        
        return myok($data);
    }
    /**
     * 接单
     * @return [type] [description]
     */
    public function accept()
    {
        $id   = input('id');
        $data = HawaList::liststate($id);
        if (empty($data)) {
            return myerr('没有找到需要的订单');
        }
        $data = $data['msg'];
        if ($data['State'] !== HawaList::STATEWAIT) {
            return myerr('目前订单状态无法接单');
        }
        $rdata = ['State' => HawaList::STATEWAITOK, 'id' => $id, 'ArriveTime' => input('time')];
        HawaList::user_reinfo($rdata);
        $data['ArriveTime'] = input('time');
        $sb                 = Sendmessage::Orderhawa(3, $id, $data);
        if (!$sb['code']) {
            return myok('已接单，' . $sb['msg'] . '，请主动联系产废单位');
        }
        return myok('已接单');
    }
    /**
     * 核实订单
     * 确认子订单数量
     * 业务员确定，判定数据是否调整过。
     * 调整过的话要求用户二次确认。
     * @return [type] [description]
     */
    public function confrimorder()
    {
        $data                = input('post.');
        $data['goodid']      = explode(',', $data['goodid']);
        $data['weight']      = explode(',', $data['weight']);
        $data['Box']         = explode(',', $data['Box']);
        $data['BoxCount']    = explode(',', $data['BoxCount']);
        $data['GoodName']    = explode(',', $data['GoodName']);
        $data['ObjectState'] = explode(',', $data['ObjectState']);
        $data['Harmful']     = explode(',', $data['Harmful']);

        //合同子订单与货物订单的关联
        if (!empty($data['Cont_DedutNum'])) {
            $data['Cont_DedutNum'] = explode(',', $data['Cont_DedutNum']);
            $data['Cont_Id']       = explode(',', $data['Cont_Id']);
        }
        //获取订单信息
        $order = HawaList::get($data['id']);
        if (empty($order) || $order->State == HawaList::STATEDELETE) {
            return myerr('没有找到您需要的订单');
        }
        if ($order->State !== HawaList::STATEWAITOK && $order->State !== HawaList::STATETRANSPORT) {
            return myerr('订单状态不允许修改');
        }
        if ($order->BussinessId !== Pub::userid()) {
            return myerr('非此订单业务员，没有权限');
        }

        //判断是否有选择运输工具
        if (empty($order->TranSportId) && empty($data['TranSportId'])) {
            return myerr('请选择运输工具');
        }

        //取消原合同所有抵消额度
        if (!empty($order['ContractId'])) {
            //判断合同是否有变更
            Contract::canceldeduct($order);
        }

        //从新抵扣新的合同信息
        if (!empty($data['Cont_Details'])) {
            $data['Cont_Details'] = json_array($data['Cont_Details'], true);
            //抵扣额度
            $data['CompanyId'] = $order->CompanyId;
            Contract::deduct($data);
        }

        // 查询关联的订单子表
        $list = Hawa::where('HawaListId', $data['id'])->select();
        //修改关联的订单子表
        $dellist = [];
        $addlist = [];
        $updlist = [];
        $upindex = 0;
        $upprice = 0; //需要增加的费用
        //判断数据是否有更新的和需要添加的
        foreach ($data['goodid'] as $key => $value) {
            $addsb = false; //烧饼为false代表没有找到对应数据
            foreach ($list as $listkey => $listvalue) {
                if ($value == $listvalue['GoodId'] && $data['GoodName'][$key] == $listvalue['GoodName']) {
                    //判断是否需要新增数据
                    $addsb = true; //找到此数据
                    //判断是否需要更新数据
                    if (((float) $data['weight'][$key] !== $listvalue['Weight']) || ($data['Box'][$key] . $data['BoxCount'][$key] . $data['GoodName'][$key] . $data['ObjectState'][$key] . $data['Harmful'][$key] !== $listvalue['Box'] . $listvalue['BoxCount'] . $listvalue['GoodName'] . $listvalue['ObjectState'] . $listvalue['Harmful'])) {
                        $updlist[$upindex] = $listvalue;
                        //重量判断
                        if ((float) $data['weight'][$key] !== $listvalue['Weight']) {
                            $updlist[$upindex]['Weight'] = $data['weight'][$key];
                            $upprice                     = $upprice + $listvalue['Price'] * ($data['weight'][$key] - $listvalue['Weight']);
                        }
                        //容器判断
                        if ($data['Box'][$key] !== $listvalue['Box']) {
                            $updlist[$upindex]['Box'] = $data['Box'][$key];
                        }

                        //容器数量判断
                        if ($data['BoxCount'][$key] !== $listvalue['BoxCount']) {
                            $updlist[$upindex]['BoxCount'] = $data['BoxCount'][$key];
                        }

                        //货物名称判断
                        if ($data['GoodName'][$key] !== $listvalue['GoodName']) {
                            $updlist[$upindex]['GoodName'] = $data['GoodName'][$key];
                        }

                        //货物状态判断
                        if ($data['ObjectState'][$key] !== $listvalue['ObjectState']) {
                            $updlist[$upindex]['ObjectState'] = $data['ObjectState'][$key];
                        }

                        //有害成分
                        if ($data['Harmful'][$key] !== $listvalue['Harmful']) {
                            $updlist[$upindex]['Harmful'] = $data['Harmful'][$key];
                        }

                        //关联合同抵扣额度
                        //因为修改之前已经将所有抵扣额度取消，所以再此处直接修改
                        if (!empty($data['Cont_DedutNum'][$key])) {
                            $updlist[$upindex]['Cont_DedutNum'] = $data['Cont_DedutNum'][$key];
                            $updlist[$upindex]['Cont_Id']       = $data['Cont_Id'][$key];
                        }

                        $upindex++;
                    }
                    break;
                }
            }
            if ($addsb == false) {
                $addlist['Box'][]         = $data['Box'][$key];
                $addlist['BoxCount'][]    = $data['BoxCount'][$key];
                $addlist['GoodName'][]    = $data['GoodName'][$key];
                $addlist['ObjectState'][] = $data['ObjectState'][$key];
                $addlist['Harmful'][]     = $data['Harmful'][$key];
                $addlist['valuelist'][]   = $data['weight'][$key];
                $addlist['goodlist'][]    = $value; //新增数据
            }
        }

        //判断数据是否有删除的数据
        foreach ($list as $listkey => $listvalue) {
            $delsb = true;
            foreach ($data['goodid'] as $key => $value) {
                if ($value == $listvalue['GoodId'] && $data['GoodName'][$key] == $listvalue['GoodName']) {
                    $delsb = false; //找到此数据
                    break;
                }
            }
            if ($delsb == true) {
                $dellist[] = $listvalue['HawaId']; //删除
                $upprice   = $upprice - $listvalue['Price'] * $listvalue['Weight'];
            }
        }

        //修改子表
        //判断是否有需要删除的
        if (!empty($dellist)) {
            Hawa::destroy($dellist);
        }
        //判断是否需要更新的数据
        if (!empty($updlist)) {
            foreach ($updlist as $key => $value) {
                $value->save();
            }

        }
        //新增数据
        if (!empty($addlist)) {
            //判断报价模式 若报价为-1 则是 业务员报价 否则为会计报价
            if ($order['QuotationListId'] == -1) {
                //业务员报价模式
                $hawa = Hawa::screate($data['id'], $addlist['goodlist'], $addlist['valuelist'], -1, $addlist);
            } else {
                //会计报价模式
                $addquot = QuotationList::get_create_question($addlist, $order['QuotationListId']);
                $hawa    = Hawa::screate($data['id'], $addlist['goodlist'], $addlist['valuelist'], $addquot['msg']['pricelist'], $addlist);
            }
        }
        $rcost = $order->QuotationCost;
        //修改主表金额
        if ($order['QuotationListId'] == -1 || empty($order['QuotationListId'])) {
            //业务员报价模式
            $order->TotalCost     = $order->TotalCost - $order->QuotationCost + $data['QuotationCost'];
            $order->QuotationCost = $data['QuotationCost'];
        } else {
            //会计报价模式
            if (!empty($upprice) || !empty($addlist) || !empty($updlist) || !empty($dellist)) {
                $quodata = QuotationList::get_create_question(
                    ['goodlist' => $data['goodid'],
                        'valuelist' => $data['weight'],
                    ],
                    $order['QuotationListId']
                );
                $order->TotalCost     = $order->TotalCost - $order->QuotationCost + $quodata['msg']['QuotationCost'];
                $order->QuotationCost = $quodata['msg']['QuotationCost'];
            }
        }

        //运输单位信息
        $transtateupdate = false; //运输单位信息变更状态
        $filedname       = ['TransitCompanyId' => '单位id', 'TransitCompanyName' => '单位名字', 'TransitCompanyAddress' => '单位地址', 'TransitNumber' => '证号', 'TransitTel' => '单位联系电话', 'TranSportId' => '工具id', 'TranSportType' => '工具类型', 'TransitBrandNumber' => '工具牌号', 'TransitDriverId' => '驾驶员id', 'TransitDrvierName' => '驾驶员名称', 'TransitDrvierTel' => '驾驶员电话', 'TransitEscortId' => '押运员id', 'TransitEscortName' => '押运员名称', 'TransitEscortTel' => '押运员电话', 'TransitUserId' => '收集员id', 'TransitEndPoint' => '终点', 'TransitStartTime' => '实际起运时间', 'TransitStartingPoint' => '起始点', 'TransitViaLand' => '经由地','ReceiptAddress'        => '收集单位地址',
            'ReceiptName'         => '收集单位名称', 'ReceiptNumberCard'  => '收集单位证号'];
        $userinfo        = UserModel::getinfo();
        $str             = '【' . $userinfo->Name . '|' . $userinfo->UserId . '】在' . date('Y-m-d H:i', time()) . '进行了信息调整：';
        $lsstr           = $str; //保存更新标题 变更完后检测是否有更改
        foreach ($filedname as $key => $value) {
            if (!empty($data[$key]) && (empty($order[$key]) || $order[$key] . '|' !== $data[$key] . '|')) {
                switch ($key) {
                    //变更运输单位将取消收集员权限
                    case 'TransitCompanyId':
                        $order['TransitUserId'] = '';
                        break;
                }
                $transtateupdate = true;
                if (!empty($order[$key])) {
                    $str = $str . '字段【运输' . $value . '】由【' . $order[$key] . '】修改为【' . $data[$key] . '】;';
                }
                $order[$key] = $data[$key];
            }
        }
        //若没有内容修改，则删掉更新标题
        if ($lsstr == $str) {
            $str = '';
        }
        if ($transtateupdate == true) {
            $order['OperationLog'] = $order['OperationLog'] . $str;
        }

        //判断是否有更新，需要通知产废单位二次确认
        if (!empty($upprice) || !empty($addlist) || !empty($updlist) || !empty($dellist) || $rcost !== $order->QuotationCost || $transtateupdate || $data['ContractId'] !== $order->ContractId) {
            //修改绑定的合同信息
            if (!empty($data['ContractId'])) {
                $order->ContractId = $data['ContractId'];
            }

            //产品名完善
            if (!empty($data['GoodName'])) {
                Goods::NamePerfect($data['goodid'], $data['GoodName']);
            }

            //有害成分完善
            if (!empty($data['Harmful'])) {
                Goods::HarmfulListPerfect($data['goodid'], $data['Harmful']);
            }

            //判断产废单位是否有注册 ，如果没有注册则直接通过
            if (!empty($order->UpUserId)) {
                $order->ConfirmState = HawaList::CONFRIMBUSS;
            } else {
                $order->ConfirmState = HawaList::CONFRIMOK;
                $order->State        = HawaList::STATETRANSPORT;
            }
        } else {
            if ($order->ConfirmState == HawaList::CONFRIMHAWA) {
                $order->ConfirmState = HawaList::CONFRIMOK;
            } else {
                if ($data['note'] == $order->LoadingNote && $order->State == HawaList::STATETRANSPORT) {
                    return myerr('订单数据无需修改');
                }
            }
            $order->State = HawaList::STATETRANSPORT;
        }

        //修改主表其他信息
        $order->LoadingTime = date('Y-m-d H:i', time());
        $order->LoadingNote = $data['note'];
        $order->save();

        if ($order->State == HawaList::STATETRANSPORT && $order->ConfirmState !== HawaList::CONFRIMBUSS) {
            return myok('订单一致，请开始运输');
        } else {
            if (empty($order->UpUserId)) {
                return myok('该订单未绑定企业管理员，系统自动通过修改。请及时运输');
            }
            $sb = Sendmessage::Orderhawa(4, $data['id'], $order);
            if (!$sb['code']) {
                return myok('订单有变更，请提示用户确认变更');
            }
            return myok('订单有变更，请提示用户确认变更');
        }
    }

    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upimg()
    {
        $type = empty(input('type')) ? 'other' : input('type');
        if (!$type == 'hawa' || !$type == 'buss' || !$type == 'acco') {
            $type = 'other';
        }
        try {
            $file = request()->file('img');
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!is_null($file)) {
            try {
                $save_path = Env::get('root_path') . 'public\\static' . '\\upimg\\hawa\\' . $type . '\\';
                $info      = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif'])->rule("date")->move($save_path);
                //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
                $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
                $image->thumb(2000, 2000)->save($save_path . '\\' . $info->getSaveName());
                if ($info) {
//getSaveName();
                    $p = $info->getFilename();
                    return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/hawa/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
                } else {
                    return json_encode(['status' => 'error', 'data' => $info->getError()]);
                }
            } catch (\Exception $e) {
                return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
            }

        } else {
            return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
        }
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
